package com.dmxh.service.impl;

import cn.hutool.core.util.StrUtil;
import com.dmxh.mapper.TbUserMapper;
import com.dmxh.pojo.Deadqueue;
import com.dmxh.pojo.TbUser;
import com.dmxh.pojo.TbUserExample;
import com.dmxh.result.Result;
import com.dmxh.result.ResultConstant;
import com.dmxh.service.UserService;
import com.dmxh.util.ShiroUtils;
import com.dmxh.vo.UserVo;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private TbUserMapper tbUserMapper;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result sendMessage(String phone) {
        //手机号非空判断
        if (phone == null) {
            return Result.response(ResultConstant.PARAM_NULL);
        }
        //手机号重复判断
        TbUserExample tbUserExample = new TbUserExample();
        tbUserExample.createCriteria().andPhoneEqualTo(phone);
        List<TbUser> tbUsers = tbUserMapper.selectByExample(tbUserExample);
        if (tbUsers.size() > 0) {
            return Result.response(ResultConstant.REPEAT_PHONE);
        }
        //发送队列消息
        rocketMQTemplate.convertAndSend("dongdongshop-t",phone);
        return Result.ok();
    }

    @Override
    public Result register(UserVo userVo) {
        //判断Redis中是否有code
        Object o = redisTemplate.boundValueOps("register:" + userVo.getPhone()).get();
        String code= o.toString().split(":")[0];
        //存在code时验证是否一致,若一致则进行注册
        if (code != null && StrUtil.equals(code, userVo.getCode())) {
            TbUser tbUser = new TbUser();
            BeanUtils.copyProperties(userVo, tbUser);
            tbUser.setCreated(new Date());
            tbUser.setUpdated(new Date());
            String salt = ShiroUtils.generateSalt(32);
            tbUser.setSalt(salt);
            String password = ShiroUtils.encryptPassword("md5", tbUser.getPassword(), salt, 7);
            tbUser.setPassword(password);
            tbUserMapper.insertSelective(tbUser);
            return Result.ok();
        } else {
            return Result.response(ResultConstant.TIME_OUT);
        }
    }

    @Override
    public TbUser queryByName(String username) {
        TbUserExample tbUserExample = new TbUserExample();
        tbUserExample.createCriteria().andUsernameEqualTo(username);
        List<TbUser> tbUsers = tbUserMapper.selectByExample(tbUserExample);
        return tbUsers.get(0);
    }

    @Override
    public TbUser queryById(long id) {
        return tbUserMapper.selectByPrimaryKey(id);
    }

}
